﻿/* author: em
 *  email: 124087198@qq.com
 */

using System;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Collections.Generic;

public class LocalConfig
{
    const int version = 1;
    static string modle = getModleName();
    static string path = Environment.GetEnvironmentVariable("LOCALAPPDATA") + "\\emSoft\\";
    static string file = modle + ".ini";

    static LocalConfig instance = new LocalConfig();
    public static LocalConfig Inst { get { return instance; } }
    Dictionary<string, string> dict;
    //string newKeys = "";      // time ticking

    public void Load () {
        string filePath = path + file;
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
        if (!File.Exists(filePath)) File.WriteAllText(filePath, "");

        dict = loadConfig(filePath);
    }
    public string Get (string key) {
        if (dict != null && dict.ContainsKey(key))
            return dict[key];
        return null;
    }
    public void Set (string key, object value) {
        if (dict == null) dict = new Dictionary<string, string>();
        dict[key] = value.ToString();
        //newKeys += key + ',';
    }
    public void Save() {
        //string[] keys = newKeys.Split(',');
        //foreach (string key in keys) {
        //}
        string[] lines = new string[dict.Count];
        int idx = 0;
        foreach (KeyValuePair<string, string>kv in dict)
            lines[idx++] = string.Format("{0}::{1}", kv.Key, kv.Value);
        File.WriteAllLines(path + file, lines);
    }

    // private functions
    static string getModleName() {
        const string tail = ".exe";
        string app = Process.GetCurrentProcess().MainModule.ModuleName;
        return app.Remove(app.LastIndexOf(tail), tail.Length);
    }
    Dictionary<string, string> loadConfig (string filePath) {
        Dictionary<string, string> d = null;
        string[] lines = File.ReadAllLines(filePath);
        foreach (string line in lines) {
            string[] vals = line.Split(new[] {"::"}, StringSplitOptions.None);
            if (vals.Length != 2) continue;
            if (d == null) d = new Dictionary<string, string>();
            if (!d.ContainsKey(vals[0])) d.Add(vals[0], vals[1]);
        }
        return d;
    }
}
